﻿using GenericHtml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WLFramework.Data;
using WLFramework.Data.Linq;
using WLFramework.DataAccess;
using WLFramework.Json;
using WLFramework.Validation;
using WLFramework.Web;

namespace SampleSite.admin.ajax
{
    /// <summary>
    /// updateRole 的摘要说明
    /// </summary>
    public class updateRole : AjaxHttpHandler
    {
        private class InputData
        {
            [Required]
            public int R_ID { get; set; }

            [Required]
            public string R_CName { get; set; }

            [Required]
            public string R_EName { get; set; }

            public string R_Description { get; set; }
        }

        public override void OnProcessRequest(HttpContext context)
        {
            InputData input;
            var errors = context.GetModel(out input);
            if (errors.Count > 0)
                throw new Exception("输入的数据格式不正确");

            using (PermissionContext db = new PermissionContext())
            {
                var app = db.sys_Roles.Where(k => k.R_ID != input.R_ID &&
                                                  k.R_CName == input.R_CName &&
                                                  k.R_State != 2)
                            .Count();
                if (app != 0)
                {
                    throw new Exception("角色名不能重复!");
                }
                
                db.BeginTransaction();

                db.sys_Roles
                  .Where(k => k.R_ID == input.R_ID &&
                              k.R_ID != 2)
                  .Update((k) =>
                    new sys_Roles()
                    {
                        R_CName = input.R_CName,
                        R_EName = input.R_EName,
                        R_Description = input.R_Description
                    });

                db.CommitTransaction();

                context.Response.Write(JSON.Instance.ToJSON(JSONResult.Success));
            }
        }
    }
}